<template>
  <el-card class="metadata-card">
    <template #header>
      <div class="card-header">
        <span>题目来源管理</span>
        <el-button type="primary" @click="showSourceDialog('add')">添加来源</el-button>
      </div>
    </template>

    <!-- 添加来源对话框 -->
    <el-dialog v-model="dialogVisible" title="添加题目来源" width="500px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="来源类型">
          <el-select v-model="form.sourceType" placeholder="请选择来源类型" style="width: 100%">
            <el-option v-for="type in sourceTypeOptions" :key="type" :label="type" :value="type" />
            <el-option label="新建类型" value="__new__" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.sourceType === '__new__'" label="新类型名称">
          <el-input v-model="form.newSourceType" placeholder="请输入新类型名称" />
        </el-form-item>

        <el-form-item label="来源内容">
          <el-input v-model="form.content" placeholder="请输入来源内容" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSourceForm">确定</el-button>
      </template>
    </el-dialog>

    <el-tabs type="border-card">
      <el-tab-pane v-for="(sourceType, index) in sourceTypes" :key="sourceType" :label="sourceType">
        <div class="source-content">
          <el-tag v-for="item in sourceContents[sourceType]" :key="item.id" closable
            @close="removeSourceOption(sourceType, item)" @click="editSourceOption(sourceType, item)">
            {{ item.title }}
          </el-tag>
          <el-input v-if="inputVisible[sourceType]" v-model="inputValue[sourceType]" size="small" style="width: 120px"
            @keyup.enter="confirmSourceOption(sourceType)" @blur="confirmSourceOption(sourceType)" />
          <el-button v-else size="small" @click="showInput(sourceType)">+ 添加</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import questionSourceService from '../../services/questionSource'

// 来源数据
const sourceTypes = ref([]) // 来源类型数组
const sourceContents = ref({}) // 来源内容对象 {类型: 内容数组}
const inputVisible = reactive({}) // 输入框可见性
const inputValue = reactive({}) // 输入框值
const editingId = ref(null) // 当前编辑项ID

// 对话框相关
const dialogVisible = ref(false)
const sourceTypeOptions = ref([])
const form = reactive({
  sourceType: '',
  newSourceType: '',
  content: ''
})

// 获取分类结构数据
const fetchMapSource = async () => {
  try {
    const response = await questionSourceService.getMapSource()

    // 设置来源类型
    sourceTypes.value = response.data.categories

    // 设置来源内容映射
    sourceContents.value = response.data.contentsMap
    // console.log('分类结构数据:', response.data)
    // 初始化输入框状态
    sourceTypes.value.forEach(type => {
      inputVisible[type] = false
      inputValue[type] = ''
    })

    // console.log('获取分类结构数据成功:', response.data)
  } catch (error) {
    console.error('获取分类结构数据失败:', error)
    ElMessage.error(`获取分类结构数据失败: ${error.message}`)
    sourceTypes.value = []
    sourceContents.value = {}
  }
}

// 显示添加来源对话框
const showSourceDialog = async () => {
  try {
    // 获取所有来源类型用于选择
    const response = await questionSourceService.getAllSourceTypes()
    sourceTypeOptions.value = response.data

    // 重置表单
    form.sourceType = ''
    form.newSourceType = ''
    form.content = ''

    dialogVisible.value = true
  } catch (error) {
    ElMessage.error(`获取来源类型失败: ${error.message}`)
  }
}

// 提交来源表单
const submitSourceForm = async () => {
  try {
    const sourceType = form.sourceType === '__new__' ? form.newSourceType : form.sourceType

    if (!sourceType || !form.content) {
      ElMessage.warning('请填写完整的来源信息')
      return
    }

    await questionSourceService.createQuestionSource({
      sourceType,
      sourceContent: form.content  // 保持参数名不变，api.js已做转换
    })

    ElMessage.success('添加来源成功')
    dialogVisible.value = false
    await fetchMapSource() // 刷新数据
  } catch (error) {
    ElMessage.error(`${error.message}`)
  }
}

// 原有功能保持不变
const showInput = (type) => {
  inputVisible[type] = true
}

const confirmSourceOption = async (type) => {
  if (inputValue[type]) {
    const contentData = {
      sourceType: type,
      sourceContent: inputValue[type]
    }

    try {
      if (editingId.value) {
        // 更新模式
        await questionSourceService.updateQuestionSource(editingId.value, contentData)
        ElMessage.success('更新成功')
      } else {
        // 创建模式
        try {
          const response = await questionSourceService.createQuestionSource(contentData);
          ElMessage.success(`添加来源成功`);
        }
        catch (error) {
          ElMessage.error(error.message);
        }
      }

      // 刷新整个数据
      await fetchMapSource()
    } catch (error) {
      ElMessage.error(editingId.value ? '更新失败' : '添加失败')
    }
    editingId.value = null
  }
  inputVisible[type] = false
  inputValue[type] = ''
}

const editSourceOption = (type, item) => {
  inputValue[type] = item.sourceContent
  editingId.value = item.id
  inputVisible[type] = true
}

const removeSourceOption = async (type, item) => {
  try {
    await questionSourceService.deleteQuestionSource(item.id)
    // 刷新整个数据
    await fetchMapSource()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error(`删除失败: ${error.message}`)
  }
}

onMounted(() => {
  fetchMapSource()
})

defineExpose({
  fetchMapSource
})
</script>

<style scoped>
.metadata-card {
  margin-top: 0px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #eee;
}

.metadata-card :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
  padding: 15px 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}

.card-header span {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

:deep(.el-dialog__title) {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 12px 20px;
  background: #f5f7fa;
  border-top: 1px solid #eee;
}

:deep(.el-tabs) {
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

:deep(.el-tabs__header) {
  background: #f8f9fa;
  margin: 0;
}

:deep(.el-tab-pane) {  /** 题目来源管理内部的具体内容框的大小 */
  padding: 15px;
  min-height: 45px;
}

.source-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  min-height: 40px;
}

.el-tag {
  cursor: pointer;
  margin-right: 0;

  padding: 6px 10px;
  border-radius: 4px;
  font-size: 0.85rem;
  transition: all 0.2s ease;
  
}

.el-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

:deep(.el-input) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  :deep(.el-tab-pane) {
    padding: 12px;
  }
  
  .source-content {
    gap: 8px;
  }
  
  .metadata-card {
    margin-top: 12px;
  }
}
</style>
